#include <iostream>
#include <fstream>
#include <stdexcept>
#include <stdlib.h>
#include <pthread.h>

using namespace std;

static int exit_flag = 1;

/* The name this program was run with. */
string program_name;
string program_ini;

int port;      // listen port
int thread;    // sever thread number

bool get_config(string file, string name, string &value)
{
	ifstream ifs(file.c_str());
	char line[BUFSIZ], opt[sizeof(line)], val[sizeof(line)];

	if (!ifs)
		return false;

	while (ifs.getline(line, BUFSIZ).good()) {
		*opt = 0, *val = 0;

		int n = 0;
		while (line[n] == ' ' || line[n] == '\t')
			n++;

		// Ignore empty lines and comments
		if (line[n] == '#' || line[n] == '\n')
			continue;

		if (sscanf(line + n, "%[^= \t]%*[ \t=]%[^ \t\r\n#]", opt, val) != 2)
			return false;

		if (!name.compare(opt)) {
			value = val;
			return true;
		}	
	}
	
	return false;	
}

void init_config()
{
	string v;

	if (!(get_config(program_ini, "port", v) && (port = atoi(v.c_str())))) {
		cout << "get port error!"
		exit(EXIT_FAILURE);	
	}

	if (!(get_config(program_ini, "thread", v) && (thread = atoi(v.c_str())))) {
		cout << "get thread num error!"
		exit(EXIT_FAILURE);
	}
}


void listener(void *arg)
{
	pthread_detach(pthread_self());

	while (exit_flag == 0) {

	}
}

void server(void *arg)
{
	pthread_detach(pthread_self());

	while (exit_flag == 0) {

	}
} 

int main(int argc, char **argv)
{
	int n;

	//daemon(1, 1);

	/* change work path */
	{
		string p = argv[0];
		chdir(p.erase(p.find_last_of('/')).c_str());
	}

	program_name = argv[0];
	program_name = ((n = program_name.find_last_of('/')) == string::npos ? program_name : program_name.substr(n + 1));
	program_ini = program_name + ".ini";
	
	init_config();

	exit(0);

	pthread_t lpid;
	pthread_t spid[thread];

	while (exit_flag == 0)
		sleep(1);

	exit(0);
}
